package com.utility.des;

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * DES目前已经可以破解，所以如果是比较重要的数据最好不要采用该加密方案，可以采用改进AES加密
 */
public class DESUtility {
	/**
     * 偏移变量，固定占8位字节
     */
    private final static String IV_PARAMETER = "12345678";
    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "DES";
    /**
     * 加密/解密算法-工作模式-填充模式
     */
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
    /**
     * 默认编码
     */
    private static final String CHARSET = "UTF-8";
    
    /**
     * 根据给定的密钥生成密钥KEY
     * @param password 给定的密钥
     * @return
     */
    private static Key generateKey(String password){
    	try{
    		DESKeySpec desKeySpec = new DESKeySpec(password.getBytes(CHARSET));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            return keyFactory.generateSecret(desKeySpec);
    	}catch(Exception e){
    		throw new RuntimeException(e);
    	}
    }
    
    /**
     * 将给定的字符串使用des加密
     * @param key
     * @param source
     * @return
     */
    public static String encrypt(String key, String source) {
        try {
            Key secretKey = generateKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] bytes = cipher.doFinal(source.getBytes(CHARSET));
            return new String(Base64.getEncoder().encode(bytes));
        } catch (Exception e) {
        	throw new RuntimeException(e);
        }
    }

    /**
     * 将给定的字符串使用des解密
     * @param key
     * @param source
     * @return
     */
    public static String decrypt(String key, String source) {
        try {
            Key secretKey = generateKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            return new String(cipher.doFinal(Base64.getDecoder().decode(source.getBytes(CHARSET))), CHARSET);
        } catch (Exception e) {
        	throw new RuntimeException(e);
        }
    }
    
    public static void main(String[] args) {
    	String key = "12afsad!`";
		String s = "{我是中国:sdfdssssssssssssssssssssssssssssssssfw大凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞凤飞飞}";
		String ss = encrypt(key, s);
		System.out.println(ss);
		System.out.println(decrypt(key, ss));
	}
}
